package cn.ljy.authority.config.security.user;

import cn.ljy.authority.model.SysUserLoginLog;
import cn.ljy.authority.model.dto.SysUserAuthority;
import cn.ljy.authority.service.SysUserLoginLogService;
import cn.ljy.authority.service.SysUserTokenService;
import cn.ljy.common.model.result.ResponseData;
import cn.ljy.common.utils.ResponseUtil;
import cn.ljy.common.utils.requests.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 处理后台管理员登录验证成功后的类
 */
@Slf4j
@Component
public class UserAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysUserLoginLogService sysUserLoginLogService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        SysUserAuthority userAuthority = (SysUserAuthority) authentication.getPrincipal();
        //登录成功后生成token，并将token存入redis
        String token= sysUserTokenService.saveUserToken(userAuthority);
        //将token存入token
        HashMap<String, String> map = new HashMap<>();
        map.put("accessToken",token);
        //保存登录成功的日志
        SysUserLoginLog sysUserLoginLog=new SysUserLoginLog();
        // 根据不同登录方式获取用户标识
        String username = request.getParameter("username");
        String tel = request.getParameter("tel");
        sysUserLoginLog.setUsername(userAuthority.getUsername());
        if (username != null && !username.isEmpty()) {
            sysUserLoginLog.setUsername(userAuthority.getUsername());
            sysUserLoginLog.setLoginType((short) 1);
        } else if (tel != null && !tel.isEmpty()) {
            sysUserLoginLog.setUsername(tel); // 使用手机号作为用户名记录
            sysUserLoginLog.setLoginType((short) 2);
        }
        sysUserLoginLog.setLoginResult(true);
        sysUserLoginLog.setIp(RequestUtil.getClientIp());
        //根据账户名获取对应账户的id
        sysUserLoginLog.setUser(userAuthority);
        sysUserLoginLogService.save(sysUserLoginLog);
        ResponseUtil.responseJson(response, ResponseData.success(map));
    }
}
